<template>
  <div class="about">
    <div id="xinpian">
      <div>芯片id</div>
      <input type="text" class="long-input" v-model="chipValue" placeholder="请输入芯片id" />

    </div>
    <button style="margin-top:1rem;" @click="query">查询</button>


    <div class="sensor" v-if="sensors.length > 0">
      <div v-for="(sensor, index) in sensors" :key="index">
        <div>{{ sensor.name }}</div>
        <div class="sub">
          <div class="row" v-for="(field, fieldNameIndex) in sensorFields" :key="fieldNameIndex">
            <div>{{ field.label }}</div>
            <input type="text" class="long-input" :value="sensor[field.fieldName]"
              @input="updateSensorValue(index, field.fieldName, $event.target.value)" placeholder="" />
          </div>
        </div>

      </div>
      <button style="margin-top:1rem;" v-if="sensors.length > 0" @click="sendData">修改参数</button>
    </div>
  </div>
</template>

<script>
// 引入axios
import axios from "axios";

export default {
  data() {
    return {
      chipValue: "",
      sensors: []
    };
  },
  methods: {
    updateSensorValue(index, fieldName, value) {
      this.sensors[index][fieldName] = value;  
    },
    async query() {

      const url = "http://127.0.0.1/querysensor";
      const data = {
        chipid: this.chipValue,
      };

      // 使用axios发送POST请求
      const rev = await axios.post(url, data);
      this.sensors = rev.data;
  
    },
    tohex(id, str) {
      let data_int = 0;
      console.log(id, str);
      if (id == "08") {
        data_int = Number(str) * 10;

      } else {
        data_int = Number(str);
      }
      return data_int.toString(16);

    },
    async sendData() {
      // 假设你要发送POST请求到这个URL
      const url = "http://127.0.0.1/updateparam";
      let data = "";
      for (let i = 0; i < this.sensors.length; i++) {
        data = data + this.sensors[i].sensorid + this.sensors[i].funid + this.sensors[i].regid + this.tohex(this.sensors[i].sensorid, this.sensors[i].param) + ","
      }
      data = this.chipValue + "," + data.slice(0, -1);
      console.log(data);
      // const data = this.chipValue+
      axios.post(url, { data: data });
    

    },
  },
  computed: {
    sensorFields() {
      return [
        { label: '传感器id', fieldName: 'sensorid' },
        { label: '功能码', fieldName: 'funid' },
        { label: '寄存器地址', fieldName: 'regid' },
        { label: '参数', fieldName: 'param' }
      ];
    }
  },
  mounted() {
    this.query();
  },
};
</script>

<style>

</style>
